using System;
using System.Collections.Generic;
using System.Linq;
namespace TemplateWeb.Models.Repositories
{
	#region using
	using TemplateWeb.Models;
	using TemplateWeb.Helpers;
	using System.Web.Security;
	using TemplateWeb.Models.ViewModels;
	#endregion
	public class NguoiDungRepository
	{
		public int TotalItem { get; set; }
        public List<NguoiDungInfo> SelectManagers()
        {
            List<NguoiDungInfo> lstItem = new List<NguoiDungInfo>();
            try
            {
                MembershipUserCollection userCollection = Membership.GetAllUsers();
                foreach (MembershipUser user in userCollection)
                {
                    var roleForUser = Roles.GetRolesForUser(user.UserName)[0];
                    if (roleForUser.ToUpper() == "ADMIN")
                    {
                        NguoiDungInfo userInfo = new NguoiDungInfo
                        {
                            BaseInfo = new NguoiDungBaseInfo
                            {
                                ID = (Guid)user.ProviderUserKey,
                                UserName = user.UserName,
                                Email = user.Email,
                                Role = Roles.GetRolesForUser(user.UserName)[0]
                            },
                            ExtraInfo = SelectByID((Guid)user.ProviderUserKey)
                        };
                        lstItem.Add(userInfo);
                    }
                }
                TotalItem = lstItem.Count;
                return lstItem;
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    CommonLogging.Logger.Error("NguoiDung - SelectAll: " + ex.InnerException.Message.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty));
                else
                    CommonLogging.Logger.Error("NguoiDung - SelectAll: " + ex.Message.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty));
                return lstItem;
            }	
        }

		public List<NguoiDungInfo> SelectAll(string role)
		{
            List<NguoiDungInfo> lstItem = new List<NguoiDungInfo>();
            try
            {
                MembershipUserCollection userCollection = Membership.GetAllUsers();
                foreach (MembershipUser user in userCollection)
                {
                    var roleForUser = Roles.GetRolesForUser(user.UserName)[0];
                    if (role.ToUpper() == "SUPERADMIN")
                    {
                        if (roleForUser.ToUpper() != "SUPERADMIN")
                        {
                            NguoiDungInfo userInfo = new NguoiDungInfo
                            {
                                BaseInfo = new NguoiDungBaseInfo
                                {
                                    ID = (Guid)user.ProviderUserKey,
                                    UserName = user.UserName,
                                    Email = user.Email,
                                    Role = Roles.GetRolesForUser(user.UserName)[0]
                                },
                                ExtraInfo = SelectByID((Guid)user.ProviderUserKey)
                            };
                            lstItem.Add(userInfo);
                        }
                    }
                    else if (role.ToUpper() == "ADMIN")
                    {
                        if (roleForUser.ToUpper() != "SUPERADMIN" && roleForUser.ToUpper() != "ADMIN")
                        {
                            NguoiDungInfo userInfo = new NguoiDungInfo
                            {
                                BaseInfo = new NguoiDungBaseInfo
                                {
                                    ID = (Guid)user.ProviderUserKey,
                                    UserName = user.UserName,
                                    Email = user.Email,
                                    Role = Roles.GetRolesForUser(user.UserName)[0]
                                },
                                ExtraInfo = SelectByID((Guid)user.ProviderUserKey)
                            };
                            lstItem.Add(userInfo);
                        }
                    }
                }
                TotalItem = lstItem.Count;
                return lstItem;
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    CommonLogging.Logger.Error("NguoiDung - SelectAll: " + ex.InnerException.Message.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty));
                else
                    CommonLogging.Logger.Error("NguoiDung - SelectAll: " + ex.Message.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty));
                return lstItem;
            }	
		}

		public List<NguoiDungInfo> SelectPaging(int page, int pageSize, string role)
		{
			List<NguoiDungInfo> lstItem = new List<NguoiDungInfo>();
            try
            {
                MembershipUserCollection userCollection = Membership.GetAllUsers();
                foreach (MembershipUser user in userCollection)
                {
                    var roleForUser = Roles.GetRolesForUser(user.UserName)[0];
                    if (role.ToUpper() == "SUPERADMIN")
                    {
                        if (roleForUser.ToUpper() != "SUPERADMIN")
                        {
                            NguoiDungInfo userInfo = new NguoiDungInfo
                            {
                                BaseInfo = new NguoiDungBaseInfo
                                {
                                    ID = (Guid)user.ProviderUserKey,
                                    UserName = user.UserName,
                                    Email = user.Email,
                                    Role = Roles.GetRolesForUser(user.UserName)[0]
                                },
                                ExtraInfo = SelectByID((Guid)user.ProviderUserKey)
                            };
                            lstItem.Add(userInfo);
                        }
                    }
                    else if (role.ToUpper() == "ADMIN")
                    {
                        if (roleForUser.ToUpper() != "SUPERADMIN" && roleForUser.ToUpper() != "ADMIN")
                        {
                            NguoiDungInfo userInfo = new NguoiDungInfo
                            {
                                BaseInfo = new NguoiDungBaseInfo
                                {
                                    ID = (Guid)user.ProviderUserKey,
                                    UserName = user.UserName,
                                    Email = user.Email,
                                    Role = Roles.GetRolesForUser(user.UserName)[0]
                                },
                                ExtraInfo = SelectByID((Guid)user.ProviderUserKey)
                            };
                            lstItem.Add(userInfo);
                        }
                    }
                }
                TotalItem = lstItem.Count;
                if (pageSize > 0)
                {
                    int startIndex, itemCount;
                    startIndex = (page - 1) * pageSize;
                    itemCount = pageSize;
                    if (startIndex + itemCount > lstItem.Count)
                        itemCount = lstItem.Count - startIndex;
                    lstItem = lstItem.GetRange(startIndex, itemCount);
                }
                return lstItem;
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    CommonLogging.Logger.Error("NguoiDung - SelectPaging: " + ex.InnerException.Message.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty));
                else
                    CommonLogging.Logger.Error("NguoiDung - SelectPaging: " + ex.Message.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty));

                return lstItem;
            }
		}

		public NguoiDungInfo SelectByUserName(string username)
		{
            try
            {
                var user = Membership.GetUser(username);
                NguoiDungInfo userInfo = new NguoiDungInfo
                {
                    BaseInfo = new NguoiDungBaseInfo
                    {
                        ID = (Guid)user.ProviderUserKey,
                        UserName = user.UserName,
                        Email = user.Email,
                        Role = Roles.GetRolesForUser(user.UserName)[0]
                    },
                    ExtraInfo = SelectByID((Guid)user.ProviderUserKey)
                };
                TotalItem = 1;
                return userInfo;
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    CommonLogging.Logger.Error("NguoiDung - SelectByUserName: " + ex.InnerException.Message.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty));
                else
                    CommonLogging.Logger.Error("NguoiDung - SelectByUserName: " + ex.Message.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty));

                return new NguoiDungInfo();
            }
			
		}

		public NguoiDung SelectByID(Guid id)
		{
            try
            {
                var item = DataContext.Instance.NguoiDung.SingleOrDefault(dmw => dmw.ID == id);
                if (item != null)
                    return item;
                return new NguoiDung();
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    CommonLogging.Logger.Error("NguoiDung - SelectByID: " + ex.InnerException.Message.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty));
                else
                    CommonLogging.Logger.Error("NguoiDung - SelectByID: " + ex.Message.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty));
                return new NguoiDung();
            }	
		}

		public List<NguoiDungInfo> RetrieveByID(Guid id)
		{
            var lst = new List<NguoiDungInfo>();
            try
            {
                var item = DataContext.Instance.NguoiDung.SingleOrDefault(dmw => dmw.ID == id);
                var baseinfo = new NguoiDungBaseInfo
                {
                    ID = item.ID,
                    UserName = item.aspnet_Users.UserName,
                    Email = Membership.GetUser(item.ID).Email,
                    Role = Roles.GetRolesForUser(item.aspnet_Users.UserName)[0]
                };
                if (item != null)
                    lst.Add(new NguoiDungInfo { BaseInfo = baseinfo, ExtraInfo = item });
                return lst;
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    CommonLogging.Logger.Error("NguoiDung - RetrieveByID: " + ex.InnerException.Message.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty));
                else
                    CommonLogging.Logger.Error("NguoiDung - RetrieveByID: " + ex.Message.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty));
                
                return lst;
            }
			
		}

		public bool Delete(Guid id)
		{
			try
			{
				var item = DataContext.Instance.NguoiDung.FirstOrDefault(p => p.ID == id);
				DataContext.Instance.NguoiDung.DeleteObject(item);
				DataContext.Instance.SaveChanges();
				Membership.DeleteUser(Membership.GetUser(id).UserName, true);
				return true;
			}
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    CommonLogging.Logger.Error("NguoiDung - Delete: " + ex.InnerException.Message.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty));
                else
                    CommonLogging.Logger.Error("NguoiDung - Delete: " + ex.Message.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty));

                return false;
            }
		}

		public bool Save()
		{
			try
			{
				DataContext.Instance.SaveChanges();
				return true;
			}
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    CommonLogging.Logger.Error("NguoiDung - Save: " + ex.InnerException.Message.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty));
                else
                    CommonLogging.Logger.Error("NguoiDung - Save: " + ex.Message.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty));

                return false;
            }
		}

		public bool Insert(AddNguoiDungViewModel obj, ref string errorText)
		{
			errorText = "";
			try
			{
				MembershipCreateStatus createStatus;
				MembershipUser newUser = Membership.CreateUser(obj.Info.BaseInfo.UserName, obj.Info.BaseInfo.Password, obj.Info.BaseInfo.Email, "What is your favouritr color?", "Black Or White", true, out createStatus);
				switch (createStatus)
				{
					case MembershipCreateStatus.Success:
						Roles.AddUserToRole(obj.Info.BaseInfo.UserName, obj.Info.BaseInfo.Role);
						var extraInfo = new NguoiDung
						{
							ID = (Guid)newUser.ProviderUserKey,
                            HoTen = string.Empty,
                            Phone = string.Empty,
                            NickName = string.Empty
						};
						DataContext.Instance.NguoiDung.AddObject(extraInfo);
						DataContext.Instance.SaveChanges();
						break;
					case MembershipCreateStatus.DuplicateUserName:
						errorText = "Người dùng này đã tồn tại, vui lòng nhập vào tên người dùng khác!";
						break;
					case MembershipCreateStatus.DuplicateEmail:
						errorText = "Địa chỉ Email bạn vừa nhập vào đã tồn tại, vui lòng nhập địa chỉ email khác!";
						break;
					case MembershipCreateStatus.InvalidEmail:
						errorText = "Địa chỉ Email không hợp lệ, vui lòng nhập lại.";
						break;
					case MembershipCreateStatus.InvalidPassword:
						errorText = "Mật khẩu phải có độ dài ít nhất 7 kí tự. Trong đó có 1 kí tự Alpha (~@#$%^&*).";
						break;
					default:
						errorText = "Có 1 lỗi gì đó, tài khoản của bạn chưa được khởi tạo.";
						break;
				}
				if (errorText != "")
				{
					return false;
				}
				return true;
			}
            catch (Exception ex)
            {
                errorText = "Có 1 lỗi gì đó, tài khoản của bạn chưa được khởi tạo.";
                if (ex.InnerException != null)
                    CommonLogging.Logger.Error("NguoiDung - Insert: " + ex.InnerException.Message.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty));
                else
                    CommonLogging.Logger.Error("NguoiDung - Insert: " + ex.Message.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty));

                return false;
            }
		}

		public int GetTotalItem(string role)
		{
			int count = 0;
			MembershipUserCollection userCollection = Membership.GetAllUsers();
			foreach (MembershipUser user in userCollection)
			{
				var roleForUser = Roles.GetRolesForUser(user.UserName)[0];
				if (role.ToUpper() == "SUPERADMIN")
				{
					if (roleForUser.ToUpper() != "SUPERADMIN")
					{
						count++;
					}
				}
				else if (role.ToUpper() == "ADMIN")
				{
					if (roleForUser.ToUpper() != "SUPERADMIN" && roleForUser.ToUpper() != "ADMIN")
					{
						count++;
					}
				}
			}
			return count;
		}

		public int GetTotalPage(string role)
		{
			int RecordCount = GetTotalItem(role);
			int PageSize = WebConfiguration.NumNguoiDungPerPage;
			return (RecordCount / PageSize) + ((RecordCount % PageSize == 0) ? 0 : 1);
		}

	}
}